package com.work.formaldehyde.activity;

import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.Time;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.util.Util;
import com.hb.dialog.myDialog.MyAlertInputDialog;
import com.umeng.analytics.MobclickAgent;
import com.work.formaldehyde.R;
import com.work.formaldehyde.activityadapter.JianCeZuoAdapter;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.Url;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;


public class AddCeLiangActivity extends Activity implements View.OnClickListener {
    private ImageView comeback, loction_xia_img_one;
    private RelativeLayout kqr;
    private TextView today_time, weizhi;
    private EditText wendu, shidu, shuju;
    private RelativeLayout submit;
    private String wendustr, shidustr, shujustr;
    private LinearLayout sjhm;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApiUtils.ActivityIsLogin(this, 0);
        setContentView(R.layout.activity_addceliang);
        comeback = findViewById(R.id.jiance_comeback);
        comeback.setOnClickListener(this);
        if (ApiUtils.isNetworkConnected(AddCeLiangActivity.this))
            init();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private String now_time, now_address = "主卧";
    private String zhuangtai = "0", wendus = "", shidus = "", jiaquans = "",updatestrid="";

    /**
     * 初始加载
     */
    public void init() {
        Intent getints = getIntent();
        zhuangtai = getints.getStringExtra("zhuangtai");
        sjhm = findViewById(R.id.sjhm);
        sjhm.setOnClickListener(this);
        weizhi = findViewById(R.id.weizhi);
        DateTimePpicke(this);
        wendu = findViewById(R.id.wendu);
        wendu.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                for (int i = 41; i <= 99; i++) {
                    if (wendu.getText().toString().equals(String.valueOf(i))) {
                        wendu.setText("");
                        ApiUtils.SetToast(AddCeLiangActivity.this, "请输入0-40之间的数字");
                    }
                }
            }
        });
        shidu = findViewById(R.id.shidu);
        shidu.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                for (int i = 101; i <= 999; i++) {
                    if (shidu.getText().toString().equals(String.valueOf(i))) {
                        shidu.setText("");
                        ApiUtils.SetToast(AddCeLiangActivity.this, "请输入0-100之间的数字");
                    }
                }
            }
        });
        shuju = findViewById(R.id.shuju);
        submit = findViewById(R.id.submit);
        submit.setOnClickListener(this);
        kqr = findViewById(R.id.kqr);
        kqr.setOnClickListener(this);
        loction_xia_img_one = findViewById(R.id.loction_xia_img_one);
        Init();
        today_time = findViewById(R.id.today_time);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        now_time = formatter.format(curDate);
        today_time.setText(formatter.format(curDate));
        weizhi.setText(now_address);
        shuju.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                /*判断是否是“GO”键*/
                if (i == EditorInfo.IME_ACTION_SEARCH || i == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    String keytag = shuju.getText().toString().trim();
                    if (TextUtils.isEmpty(keytag)) {
                        return false;
                    }
                    if (ApiUtils.isNetworkConnected(AddCeLiangActivity.this)) {
                        tijiaoshuju();
                    } else
                        ApiUtils.SetToast(AddCeLiangActivity.this, R.string.wangluo);
                    return true;
                }
                return false;
            }
        });
        if (zhuangtai.equals("1")) {
            wendus = getints.getStringExtra("wendu");
            shidus = getints.getStringExtra("shidu");
            jiaquans = getints.getStringExtra("jiaquan");
            updatestrid= getints.getStringExtra("id");
            wendu.setText(wendus);
            shidu.setText(shidus);
            shuju.setText(jiaquans);
        }
    }

    private Boolean kq = true;
    private JianCeZuoAdapter jianCeJiLuAdapter;
    private ArrayList<String> zhuwolist = new ArrayList<>();

    public void Init() {
        for (int is = 0; is < 3; is++) {
            if (is == 0) {
                zhuwolist.add("2");
            }
            zhuwolist.add("1");
        }
        jianCeJiLuAdapter = new JianCeZuoAdapter(zhuwolist,
                AddCeLiangActivity.this);
    }

    private PopupWindow popupWindows;

    public void windows(Context context) {
        View popupwindowviews = LayoutInflater.from(context).inflate(
                R.layout.popupwindow_zhuwo, null);
        final ListView zhuwo_check_list = popupwindowviews.findViewById(R.id.zhuwo_check_list);
        zhuwo_check_list.setAdapter(jianCeJiLuAdapter);
        zhuwo_check_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i != 3)
                    for (int is = 0; is < zhuwolist.size(); is++) {
                        if (zhuwolist.get(is).equals("2") && is != i) {
                            zhuwolist.set(is, "1");
                        }
                    }
                switch (i) {
                    case 0:
                        now_address = "主卧";
                        popupWindows.dismiss();
                        break;
                    case 1:
                        now_address = "次卧";
                        popupWindows.dismiss();
                        break;
                    case 2:
                        now_address = "客厅";
                        popupWindows.dismiss();
                        break;
                    case 3:
                        zdy();
                        popupWindows.dismiss();
                        break;
                }
                if (i != 3) {
                    weizhi.setText(now_address);
                    zhuwolist.set(i, "2");
                    jianCeJiLuAdapter.notifyDataSetChanged();
                }
            }
        });
        popupWindows = new PopupWindow(popupwindowviews, (getWindowManager().getDefaultDisplay().getWidth()) * 2 / 5,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindows.setTouchable(true);
        popupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
                loction_xia_img_one.animate().rotation(360);
                kq = true;
            }
        });
        popupWindows.setFocusable(true);
        popupWindows.setOutsideTouchable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
        popupWindows.showAsDropDown(kqr, -0, 0, Gravity.LEFT);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.jiance_comeback:
                onBackPressed();
                break;
            case R.id.kqr:
                loction_xia_img_one.setPivotX(loction_xia_img_one.getWidth() / 2);
                loction_xia_img_one.setPivotY(loction_xia_img_one.getHeight() / 2);
                if (kq) {
                    loction_xia_img_one.animate().rotation(180);
                    kq = false;
                    windows(AddCeLiangActivity.this);
                }
                break;
            case R.id.submit:
                tijiaoshuju();
                break;
            case R.id.sjhm:
                pvTime.show();
                break;
        }
    }

    public void tijiaoshuju() {
        wendustr = wendu.getText().toString();
        shidustr = shidu.getText().toString();
        shujustr = shuju.getText().toString();
        if (!wendustr.equals("") && !shidustr.equals("") && !shujustr.equals("") && !Url.USER_ID.equals("")) {
            ApiUtils.windows(AddCeLiangActivity.this, submit, "提交中...");
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    ApiUtils.closepopup();
                }
            }, 10000);
            okHttp_postFromParameters();
        } else if (wendustr.equals("")) {
            wendu.setFocusable(true);
            wendu.setFocusableInTouchMode(true);
            wendu.requestFocus();
            ApiUtils.SetToast(AddCeLiangActivity.this, R.string.addceliangmsg);
        } else if (shidustr.equals("")) {
            shidu.setFocusable(true);
            shidu.setFocusableInTouchMode(true);
            shidu.requestFocus();
            ApiUtils.SetToast(AddCeLiangActivity.this, R.string.addceliangmsg1);
        } else if (shujustr.equals("")) {
            shuju.setFocusable(true);
            shuju.setFocusableInTouchMode(true);
            shuju.requestFocus();
            ApiUtils.SetToast(AddCeLiangActivity.this, R.string.addceliangmsg2);
        } else if (Url.USER_ID.equals("")) {
            Intent is_login = new Intent(AddCeLiangActivity.this, LoginActivity.class);
            startActivity(is_login, ActivityOptions.makeSceneTransitionAnimation(AddCeLiangActivity.this).toBundle());
            ApiUtils.SetToast(AddCeLiangActivity.this, "请先登录");
        }
    }

    private void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = null;
                    Request request = null;
                    if (zhuangtai.equals("0")) {
                        formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("times", now_time).add("temp", wendustr).add("humidity", shidustr).add("hcho", shujustr).add("room", now_address)
                                .build();
                        request = new Request.Builder().url(Url.ADDCELIANG).post(formBody).build();
                    } else {
                        formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("recordid", updatestrid).add("times", now_time).add("temp", wendustr).add("humidity", shidustr).add("hcho", shujustr).add("room", now_address)
                                .build();
                        request = new Request.Builder().url(Url.ADDCELIANG).post(formBody).build();
                    }
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot1.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public void zdy(){
        final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(this).builder()
                .setTitle("请输入")
                .setEditText("");
        myAlertInputDialog.setPositiveButton("确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                now_address = myAlertInputDialog.getResult();
                weizhi.setText(now_address);
                myAlertInputDialog.dismiss();
            }
        }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myAlertInputDialog.dismiss();
            }
        });
        myAlertInputDialog.show();
    }

    public Handler gethot1 = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        onBackPressed();
                        JianCeJiLuActivity.isboole = true;
                        ApiUtils.SetToast(AddCeLiangActivity.this, "操作成功");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    TimePickerView pvTime;
    int sid = 0;
    String dangqiantime = "", jieshutime = "";

    public void DateTimePpicke(Context context) {
        Calendar selectedDate = Calendar.getInstance();
        Time t = new Time();
        t.setToNow(); // 取得系统时间。
        int year = t.year;
        int month = t.month;
        int day = t.monthDay;
        int mWay = selectedDate.get(Calendar.DAY_OF_WEEK);
//        String mway = null;
//        mway = Apiutils.GetWeekday(mWay);
        int h = t.hour;
        int m = t.minute;
//        bwl_tiem.setText(year + "年" + (month + 1) + "月" + day + "日" + " 周" + mway + " " + h + ":" + m);
        selectedDate.set(year, month, day);
        pvTime = new TimePickerBuilder(context, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1;
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                int mway = calendar.get(Calendar.DAY_OF_WEEK);
                int h = calendar.get(Calendar.HOUR_OF_DAY);
                jieshutime = year + "-" + month + "-" + day;
                today_time.setText(jieshutime);
                now_time=jieshutime;
//                bwl_tiem.setText(year + "年" + month + "月" + day + "日" + " 周" + Apiutils.GetWeekday(mway) + " " + h + ":" + calendar.get(Calendar.MINUTE));
//                gettimestr = year + "年" + month + "月" + day + "日" + " " + h + ":" + calendar.get(Calendar.MINUTE);
            }
        }).setDate(selectedDate)
                .setSubmitColor(R.color.text_black40)
                .setCancelColor(R.color.text_black40)
                .setOutSideCancelable(false)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "时", "分", "")
                .build();
    }
}
